package com.example.redisrabbitesintegeation.aspect;

import com.example.redisrabbitesintegeation.common.exception.GlobalException;
import com.example.redisrabbitesintegeation.model.entity.News;
import com.example.redisrabbitesintegeation.mq.Producer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName NewsAspect
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/22 15:40
 * @Version 1.0
 */
@Slf4j
@Aspect
@Component
public class NewsAspect {

    @Autowired
    private Producer producer;


    /**
     * @author: kx
     * @date: 2025/10/22 16:17
     * @param joinPoint : 连接点
     * @description: 添加新闻文档信息后置通知
    */
    @AfterReturning(value = "execution(* com.example.redisrabbitesintegeation.service.impl.NewsServiceImpl.publishNews(..))")
    public void publishNews(JoinPoint joinPoint) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        try {
            producer.send((News) args[0]);
            log.info("发送消息给 RabbitMQ 成功");
        } catch (Exception e) {
            throw new GlobalException(500, "发送消息给 RabbitMQ 失败" + e.getMessage());
        }
    }

    /**
     * @author: kx
     * @date: 2025/10/22 19:14
     * @param joinPoint : 连接点
     * @description: 删除新闻文档信息后置通知
    */
    @AfterReturning(value = "execution(* com.example.redisrabbitesintegeation.service.impl.NewsServiceImpl.deleteNewsById(..))")
    public void deleteNewsById(JoinPoint joinPoint) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        try {
            String newId = String.valueOf(args[0]);
            producer.send(newId);
            log.info("发送消息给 RabbitMQ 成功");
        } catch (Exception e) {
            throw new GlobalException(500, "发送消息给 RabbitMQ 失败" + e.getMessage());
        }
    }
}
